package br.com.futibamanager.util;

import java.io.StringWriter;
import java.util.Map;

import org.apache.velocity.Template;
import org.apache.velocity.VelocityContext;
import org.apache.velocity.app.VelocityEngine;

/**
 * An utility class for template management.
 * 
 * @author diogenes.feijo
 *
 */
public abstract class TemplateManager {
	
	/**
	 * An Enum for template names.
	 * 
	 * @author diogenes.feijo
	 *
	 */
	public enum TemplateNames {
		
		/**
		 * Template name for registered user e-mail
		 */
		REGISTERED_USER_EMAIL("registeredUserEmailTemplate.vm"),
		
		USER_RECOVERY_DATA_EMAIL("userRecoveryDataEmailTemplate.vm");
		
		private String name;
		
		/**
		 * Constructor.
		 * 
		 * @param name - template's name
		 */
		private TemplateNames(String name) {
			this.name = name;
		}
		
		/**
		 * Gets the template's name
		 * 
		 * @return String
		 */
		public String getName() {
			return this.name;
		}
	}
	
	/**
	 * Gets the template.
	 * 
	 * @param templateName - the template name
	 * @param parameters - the parameters used in template
	 * 
	 * @return String
	 */
	public static String getTemplate(TemplateNames templateName, Map<String, String> parameters) {
		
        StringWriter writer = new StringWriter();
		
		try {
	        VelocityEngine velocityEngine = new VelocityEngine();
	        
	        velocityEngine.setProperty("resource.loader", "class");

	        velocityEngine.setProperty(
	        	"class.resource.loader.class", 
	        		"org.apache.velocity.runtime.resource.loader.ClasspathResourceLoader");
	        
	        velocityEngine.init();
	        
	        Template template = velocityEngine.getTemplate(templateName.getName());

	        template.merge(new VelocityContext(parameters), writer);
		} catch (Exception e) {
			throw new RuntimeException(e);
		}

		return writer.toString();
	}

}